# -*- coding: utf-8 -*-
# @Time: 2022/8/23 16:09
# @Author: 后来没有来
# @Email: panyi_20210601@163.com
# @File: orderInfo.py
# @Project: haixin
# @Software: PyCharm


from random import randint
import time
import logging

from test_case.haixin.Method.Post import post_method



from common.海信退单品费用计算 import Pay
from utils.redis_ import Redis

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(filename)s: %(lineno)d %(message)s')


class ReturnOrderItem:

    def __init__(self, userId, saleNum, skuId, salePrice, saleNum_2, skuId_2, salePrice_2, ChiobeansAmount, items):
        self.userId = userId
        self.saleNum = saleNum
        self.skuId = skuId
        self.salePrice = salePrice
        self.saleNum_2 = saleNum_2
        self.skuId_2 = skuId_2
        self.salePrice_2 = salePrice_2
        self.ChiobeansAmount = ChiobeansAmount
        self.items = items
        self.saleNo = None
        self.total_price = saleNum * salePrice + saleNum_2 * salePrice_2

    def chioFreeze(self):
        redis = Redis()
        url = "https://api-test.shwoody.com/ma/chiobeansOrder/chioFreeze"
        logging.info(f"请求地址：{url}")
        data = {
            "shopId": "80101",
            "cashNo": "0007",  # 收款机号
            "saleNo": time.strftime("%Y%m%d%H%M%S") + str(randint(10000, 99999)),  # 销售流水号  测试潮豆冻结不需要更换saleNo
            "userId": self.userId,
            "chiobeansNum": self.ChiobeansAmount
        }
        logging.info(f"入参：{data}")
        try:
            while True:
                response = post_method(data, url)
                logging.info(f"接口响应：{response}")
                if response['msg'] == "用户潮豆数量不足":
                    redis.update_available_chiobeans(self.userId, 1000)
                else:
                    break
            logging.info(f"返回订单流水saleNo:{data.get('saleNo')}\n")
            logging.info(
                "=================================调用chioFreeze接口结束=====================================\n")
            return data['saleNo']
        except Exception as err:
            logging.error("接口调用失败！")
            raise err

    def orderInfo(self):
        """
        :param amount:
        :return:
        """
        if self.ChiobeansAmount > 0:
            self.saleNo = self.chioFreeze()
        else:
            self.saleNo = time.strftime("%Y%m%d%H%M%S") + str(randint(10000, 99999))
        url = "https://api-test.shwoody.com/ma/chiobeansOrder/orderInfo"  # 注意切换环境
        # 测试潮豆冻结，注意修改支付方式
        logging.info(f"请求地址：{url}")
        data = {
            "shopId": "80101",
            "cashNo": "0007",  # 收款机号
            "saleNo": self.saleNo,
            "userId": self.userId,
            "actualPaymentPrice": self.saleNum * self.salePrice + self.saleNum_2 * self.salePrice_2,
            "paymentPrice": self.saleNum * self.salePrice + self.saleNum_2 * self.salePrice_2,  # 订单应付金额
            "orderItemList": [
                {
                    # "orderItemId": 14059,  # 订单项ID
                    "saleNum": self.saleNum,  # 销售数量
                    "marketPrice": 2,  # 商品市场单价
                    "recTime": time.strftime("%Y-%m-%d %H:%M:%S"),  # 购物时间
                    "skuId": self.skuId,  # t_order_item的sku_number
                    "salePrice": self.salePrice,  # 商品销售单价
                    "price": 0.1,  # 成本价
                    "itemActualPaymentPrice": self.saleNum * self.salePrice  # 订单项应付支付金额
                },
                {
                    # "orderItemId": "14060",  # 订单项ID
                    "saleNum": self.saleNum_2,  # 销售数量
                    "marketPrice": 1,  # 商品市场单价
                    "recTime": time.strftime("%Y-%m-%d %H:%M:%S"),  # 购物时间
                    "skuId": self.skuId_2,  # 如果skuId大于5位为计件商品，对应tz_order_item.prod_count,小于等于5位为称重商品对应prod_weight
                    "salePrice": self.salePrice_2,  # 商品销售单价
                    "price": 0.1,
                    "itemActualPaymentPrice": self.saleNum_2 * self.salePrice_2  # 订单项应付支付金额
                }
            ],
            "payList": [
                {
                    "payType": "01",  # 支付类型 0现金 01-潮豆支付  87米雅支付，区别于小程序 1和11
                    "amount": self.ChiobeansAmount  # 支付金额     潮豆支付也需要填入潮豆金额
                },
                {
                    "payType": "87",  # 支付类型 0现金 01-潮豆支付  87米雅支付，区别于小程序 1和11
                    "amount": self.saleNum * self.salePrice + self.saleNum_2 * self.salePrice_2 - self.ChiobeansAmount
                    # 支付金额     潮豆支付也需要填入潮豆金额
                }
            ]
        }
        logging.info(f"入参：{data}")
        try:
            response = post_method(data, url)
            logging.info(f"接口响应：{response}\n")
            logging.info("=================================调用orderInfo接口结束=====================================\n")
        except Exception as err:
            logging.error("接口调用失败！")
            raise err

    def refundFeeItem(self, item):
        if item['skuId'] == self.skuId:
            single_goods_price = self.saleNum * self.salePrice
            back_number = item['qty']
            total_number = self.saleNum
            salePrice = self.salePrice
        else:
            single_goods_price = self.saleNum_2 * self.salePrice_2
            back_number = item['qty']
            total_number = self.saleNum_2
            salePrice = self.salePrice_2
        pay = Pay(total_price=self.total_price, single_goods_price=single_goods_price, back_number=back_number,
                  total_number=total_number, saleNo=self.saleNo)
        if item['salePrice'] != salePrice:
            logging.error("退货计算入参单价不一致！！！！")
        url = "https://api-test.shwoody.com/ma/reOrder/refundFeeItem"
        logging.info(f"请求地址：{url}")
        data = {
            "shopId": "80101",
            "cashNo": "0007",
            "saleNo": self.saleNo,
            "userId": self.userId,
            "items": [item]
        }
        logging.info(f"入参：{data}")
        try:
            available_chiobeans = pay.available_chiobeans(self.userId)
            logging.info(f"查询账户现有潮豆：{available_chiobeans}")
            user_pv = pay.user_pv(self.userId)
            logging.info(f"查询账户现有积分：{user_pv}")
            ineffective_chiobeans = pay.ineffective_chiobeans(self.userId)
            logging.info(f"查询账户现有未生效潮豆：{ineffective_chiobeans}")
            deductionScoreAmount = pay.deductionScoreAmount()
            logging.info(f"deductionScoreAmount：{deductionScoreAmount}")
            deductionChiobeansAmount = pay.deductionChiobeansAmount()
            logging.info(f"deductionChiobeansAmount：{deductionChiobeansAmount}")
            scoreNotEffectiveChiobeansAmount = pay.scoreNotEffectiveChiobeansAmount()
            logging.info(f"scoreNotEffectiveChiobeansAmount：{scoreNotEffectiveChiobeansAmount}")
            refundChiobeansAmount = pay.refundChiobeansAmount(self.ChiobeansAmount, salePrice)
            logging.info(f"refundChiobeansAmount：{refundChiobeansAmount}")
            refundAmount = pay.refundAmount(self.ChiobeansAmount, self.userId, salePrice)
            logging.info(f"refundAmount：{refundAmount}")
            freezeChiobeanAmout = pay.freezeChiobeanAmout(self.ChiobeansAmount, self.userId)
            logging.info(f"freezeChiobeanAmout：{freezeChiobeanAmout}")
            expected_available_chiobeans = pay.expected_available_chiobeans(self.userId, self.ChiobeansAmount,
                                                                                      salePrice)
            logging.info(f"期望退款成功后账户潮豆：{expected_available_chiobeans}")
            expected_user_pv = pay.expected_user_pv(self.userId)
            logging.info(f"期望退款成功后账户积分：{expected_user_pv}")
            expected_ineffective_chiobeans = pay.expected_ineffective_chiobeans(self.userId)
            logging.info(f"期望退款成功后账户未生效潮豆：{expected_ineffective_chiobeans}")
            res = post_method(data, url)
            if res['data']['deductionScoreAmount'] == deductionScoreAmount and res['data'][
                'deductionChiobeansAmount'] == deductionChiobeansAmount and res['data'][
                'refundChiobeansAmount'] == refundChiobeansAmount and res['data'][
                'scoreNotEffectiveChiobeansAmount'] == scoreNotEffectiveChiobeansAmount and res['data'][
                'freezeChiobeanAmout'] == freezeChiobeanAmout and res['data']['refundAmount'] == refundAmount:
                logging.info(
                    f"断言成功，与期望值一致！\n扣除积分：响应：{res['data']['deductionScoreAmount']} & 实际：{deductionScoreAmount} "
                    f"\n扣除潮豆：响应：{res['data']['deductionChiobeansAmount']} & 实际：{deductionChiobeansAmount} "
                    f"\n扣除未生效潮豆：响应：{res['data']['scoreNotEffectiveChiobeansAmount']} & 实际：{scoreNotEffectiveChiobeansAmount} "
                    f"\n冻结潮豆：响应：{res['data']['freezeChiobeanAmout']} & 实际：{freezeChiobeanAmout} "
                    f"\n返还潮豆：响应：{res['data']['refundChiobeansAmount']} & 实际：{refundChiobeansAmount} "
                    f"\n返还人民币：响应：{res['data']['refundAmount']} & 实际：{refundAmount}")
            else:
                logging.info(
                    f"断言失败，与期望值不一致！\n扣除积分：响应：{res['data']['deductionScoreAmount']} & 实际：{deductionScoreAmount} "
                    f"\n扣除潮豆：响应：{res['data']['deductionChiobeansAmount']} & 实际：{deductionChiobeansAmount} "
                    f"\n扣除未生效潮豆：响应：{res['data']['scoreNotEffectiveChiobeansAmount']} & 实际：{scoreNotEffectiveChiobeansAmount} "
                    f"\n冻结潮豆：响应：{res['data']['freezeChiobeanAmout']} & 实际：{freezeChiobeanAmout} "
                    f"\n返还潮豆：响应：{res['data']['refundChiobeansAmount']} & 实际：{refundChiobeansAmount} "
                    f"\n返还人民币：响应：{res['data']['refundAmount']} & 实际：{refundAmount}")
            logging.info(f"接口响应：{res}")
            refundAmount = res['data']['refundAmount']
            logging.info(f"返回订单退款金额：{res['data']['refundAmount']}")
            logging.info(f"返回订单退款items：{data['items']}")
            logging.info("=================================调用refundFeeItem接口结束=================================\n")
            return refundAmount, pay, expected_available_chiobeans, expected_user_pv, expected_ineffective_chiobeans
        except Exception as err:
            logging.error("接口调用失败！")
            raise err

    def returnOrderItem(self, item):
        refundFeeItem = self.refundFeeItem(item)
        url = "https://api-test.shwoody.com/ma/reOrder/returnOrderItem"
        logging.info(f"请求地址：{url}")
        data = {
            "shopId": "80101",
            "cashNo": "0007",  # 收款机号
            "saleNo": self.saleNo,  # 销售流水号
            "refundSn": time.strftime("%Y%m%d%H%M%S") + str(randint(10000, 99999)),  # 退款编号
            "userId": self.userId,
            "refundSuccess": True,  # 是否成功退货
            "refundAmount": refundFeeItem[0],  # 现金支付的金额
            "items": [item]
        }
        logging.info(f"入参：{data}")
        try:
            response = post_method(data, url)
            available_chiobeans = refundFeeItem[1].available_chiobeans(self.userId)
            user_pv = refundFeeItem[1].user_pv(self.userId)
            ineffective_chiobeans = refundFeeItem[1].ineffective_chiobeans(self.userId)
            if available_chiobeans == refundFeeItem[2] and user_pv == refundFeeItem[3] and ineffective_chiobeans == \
                    refundFeeItem[4]:
                logging.info(
                    f"断言成功，与期望值一致！\n账户潮豆余额：实际：{available_chiobeans} & 期望：{refundFeeItem[2]}"
                    f"\n积分：实际：{user_pv} & 期望：{refundFeeItem[3]}\n未生效潮豆：实际：{ineffective_chiobeans} & 期望：{refundFeeItem[4]}")
            else:
                logging.info(
                    f"断言失败，与期望值不一致！\n账户潮豆余额：实际：{available_chiobeans} & 期望：{refundFeeItem[2]}"
                    f"\n积分：实际：{user_pv} & 期望：{refundFeeItem[3]}\n未生效潮豆：实际：{ineffective_chiobeans} & 期望：{refundFeeItem[4]}")
            logging.info(f"接口响应：{response}\n")
            logging.info("==============================调用returnOrderItem接口结束==================================\n")
        except Exception as err:
            logging.error("接口调用失败！")
            raise err
        finally:
            refundFeeItem[1].close_db_redis()

    def main(self):
        self.orderInfo()
        for item in self.items:
            self.returnOrderItem(item)


if __name__ == '__main__':
    items = [{"skuId": "100010", "salePrice": 2, "qty": 3},
             {"skuId": "100020", "salePrice": 2, "qty": 2}]
    # items = [{"skuId": "100010", "salePrice": 2, "qty": 2}]
    refund = ReturnOrderItem("1532568881774858240", saleNum=3, skuId="100010", salePrice=2, saleNum_2=2,
                             skuId_2="100020", salePrice_2=2, ChiobeansAmount=10, items=items)
    refund.main()
